﻿using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using GalaSoft.MvvmLight;
using LogWare.Model;

namespace LogWare.ViewModel {

	public abstract class EditableBaseViewModel : ViewModelBase, IEditableObject {
		readonly Dictionary<PropertyInfo, object> _storedProperties = new Dictionary<PropertyInfo, object>();


		public void BeginEdit() {
			IEnumerable<PropertyInfo> propertyInfos = GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance)
														 .Where(p => p.CanRead && p.CanWrite && p.GetCustomAttributes(typeof(StateAttribute), true).Any());

			foreach (var property in propertyInfos) {
				_storedProperties[property] = property.GetValue(this, null);
			}
		}

		public void EndEdit() {
			_storedProperties.Clear();
		}

		public void CancelEdit() {
			foreach (var pair in _storedProperties) {
				pair.Key.SetValue(this, pair.Value, null);
			}
		}
	}

}
